<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/5/22
 * Time: 14:47
 */

namespace App\Http\Controllers\PayInfo;

use App\Http\Controllers\Controller;
use App\Http\Controllers\PayInfo\WechatPayController;
use App\Models\Goods;
use App\Models\GoodsOrder;
use App\Models\GoodsOrderPay;
use App\Models\GoodsOrderRefund;
use App\Models\UserWechatInfo;
use App\Validate\GoodsPayInfoValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 商品支付模块
 * Class PayInfo
 * @package app\port\controller
 */
class GoodsPayInfoController extends CommonController
{
    private $validate = null;
    private $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->validate = new GoodsPayInfoValidate();
        $this->model = new GoodsOrder();
    }

    /**
     * 统一下单，获取支付所需的参数 (商品)
     * @param order_id  订单id
     */
    public function getPayInfo()
    {
        return $this->returnApi(202, '演示项目不支持在线支付！');
        // 自动验证
        if (!$this->validate->scene('get_pay_param')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $order_id = $this->request->order_id;
        $wechat_id = $this->request->user_info['wechat_id'];
        //直接修改状态
        $order_info = $this->model->get($order_id);

        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }
        if ($order_info['is_pay'] != 1) {
            return $this->returnApi(203, '网络错误');
        }

        $open_id = UserWechatInfo::where('id', $wechat_id)->value('open_id');
        $price = (int)($order_info->price * 100); //支付金额转换为分
        $wechatPayObj = new WechatPayController($order_info->order_number, '商品兑换', $price, $open_id, 'goods');
        $res = $wechatPayObj->pay();

        //  return $this->returnApi(202 , json_encode($res));

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }


    /**
     * 支付成功,验证订单状态，验证成功后修改订单状态
     * @param order_id  订单id
     */
    public function paymentSuccess()
    {
        // 自动验证
        if (!$this->validate->scene('payment_success')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $order_id = $this->request->order_id;

        //直接修改状态
        $order_info = $this->model->find($order_id);
        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }

        if ($order_info['is_pay'] == 1) {
            //自助验证状态
            $result = $this->checkWeChatPay($order_id);

            if (!$result) {
                return $this->returnApi(202, '支付失败');
            }

            return $this->returnApi(200, '支付成功', true);
        } elseif ($order_info['is_pay'] == 2) {
            return $this->returnApi(200, '支付成功', true);
        }

        return $this->returnApi(202, '支付失败');
    }

    /**
     * 修改书袋书籍状态并推送
     */
    public function modifyGoodsState($order_info)
    {
        /*  $book_id_all = NewOrderBookModel::where('order_id' , $book_info['id'])->select()->toArray();

          //修改书袋里面的书  的状态为  已购买，退款时状态退回
          foreach ($book_id_all as $key=>$val){
              NewSchoolbagModel::where('book_id' , $val['book_id'])
                  ->where('user_id', $book_info['user_id'])
                  ->update(['state'=>2 , 'change_time'=>date('Y-m-d H:i:s')]);
          }*/
        //添加系统消息
        $msg = $order_info['send_way'] == 1 ? '请及时领取' : "请关注邮递信息";
        $system_id = $this->systemAdd('商品兑换支付成功', $order_info['user_id'], $order_info['account_id'], 27, $order_info['id'], '商品兑换支付成功，' . $msg);

        if (!empty($order_info['score'])) {
            //用户积分操作  与 系统消息
            $scoreRuleObj = new \App\Http\Controllers\ScoreRuleController();
            $scoreRuleObj->scoreGoodChange($order_info['score'], $order_info['user_id'], $order_info['account_id'], '商品兑换', 0, $system_id, '商品兑换成功'); //添加积分消息
        }
    }

    /**
     * 查询微信支付系统
     */
    public function checkWeChatPay($order_id)
    {
        $order_info = $this->model::find($order_id);
        if ($order_info->is_pay == 2) {
            return true; //已支付成功
        }

        //调用微信查询接口
        $wechatPayObj = new WechatPayController($order_info->order_number);
        $result = $wechatPayObj->checkWxOrderPay();

        if (!$result) {
            return false;
            //return $this->returnData(203 , '数据异常');//实际为未查询到支付交易情况
        }
        //否则提交信息，修改数据
        //返回的$result为数组

        //微信支付订单号
        $trade_no = $result['transaction_id'];
        //订单支付时间
        $time_end = $result['time_end'];
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //   $buyer_id  = $result['device_info'];
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount = $result['total_fee'];
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount = $result['total_fee']; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount = $result['cash_fee'];

        //此处编写回调处理逻辑
        $where = array(
            'order_number' => $order_info->order_number,
            'pay_time' => $gmt_payment,
            'payment' => 1,
            'trade_no' => $trade_no,
            //    'buyer_id'		=> $buyer_id,
            //	'buyer_login_id'=>$buyer_login_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );

        //开启事务
        DB::beginTransaction();
        try {
            $cancel_end_time = Goods::where('id', $order_info['goods_id'])->value('cancel_end_time');
            $cancel_end_time = empty($cancel_end_time)  ? date('Y-m-d H:i:s') : date('Y-m-d H:i:s', strtotime("+" . $cancel_end_time . " min"));
            GoodsOrder::where('id', $order_id)->update(array('is_pay' => 2, 'change_time' => $gmt_payment, 'cancel_end_time' => $cancel_end_time));
            $goodsOrderPayModel = new GoodsOrderPay();
            $goodsOrderPayModel->add($where);

            //添加推送信息
            $this->modifyGoodsState($order_info);
            DB::commit();
            return true;    //支付成功
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }



    /**
     * 审核拒绝或无法发货，进行退款操作
     * @param order_id 订单id
     * @param refund_remark 退款备注
     */
    public function refund($order_id, $refund_remark)
    {
        $order_info = $this->model->find($order_id);
        if (empty($order_info)) {
            throw new Exception('订单获取失败');
        }
        if (empty($order_info['score'])) {
            throw new Exception('此订单无须退款');
        }
        if ($order_info['is_pay'] == 5) {
            throw new Exception('此订单已退款，无需重复操作');
        }
        if ($order_info['is_pay'] != 2) {
            throw new Exception('此订单状态异常，请联系技术处理');
        }
        if ($order_info['status'] != 1 && $order_info['status'] != 3) {
            // return $this->returnApi(202 , '此订单状态异常，请联系技术处理');
            throw new Exception('此订单状态异常，请联系技术处理');
        }
        $refund_no = get_order_id();
        $trade_no = GoodsOrderPay::where('order_number', $order_info->order_number)->value('trade_no');  //微信支付订单号

        $wxReturnMoney = new WxReturnMoneyController();
        $return_info = $wxReturnMoney->doRefund($order_info->price, $order_info->price, $refund_no, $trade_no, $order_info->order_number, $refund_remark);

        $goodsOrderRefundModel = new GoodsOrderRefund();
        $time = date('Y-m-d H:i:s');
        if ($return_info['code'] === 200) {
            //退款成功
            //  DB::beginTransaction();
            // try{
            $goodsOrderRefundModel->refund_number = $refund_no;
            $goodsOrderRefundModel->refund_id = $return_info['refund_id'];
            $goodsOrderRefundModel->refund_time = $time;
            $goodsOrderRefundModel->price = $order_info->price;
            $goodsOrderRefundModel->payment = 1;
            $goodsOrderRefundModel->status = 1;
            // $goodsOrderRefundModel->manage_id = self::$param['user_id'];
            $goodsOrderRefundModel->save();
            //修改订单状态
            $order_info->is_pay = 5;
            $order_info->refund_number = $refund_no;
            $order_info->refund_time = $time;
            $order_info->refund_remark = $refund_remark;
            //$order_info->refund_manage_id = self::$param['user_id'];
            $order_info->save();

            //添加系统消息
            $this->systemAdd('取消商品兑换成功', $order_info->user_id, $order_info->account_id, null, 28, $order_id, '取消商品兑换成功，返还兑换商品时支付的金额；退回理由: ' . $refund_remark);

            return true;
        } else {
            //添加退款日志
            $goodsOrderRefundModel->refund_number = $refund_no;
            $goodsOrderRefundModel->refund_time = $time;
            $goodsOrderRefundModel->price = $order_info->price;
            $goodsOrderRefundModel->payment = 1;
            $goodsOrderRefundModel->status = 2;
            $goodsOrderRefundModel->manage_id = null;
            if (isset($return_info['err_code'])) $goodsOrderRefundModel->error_code = $return_info['err_code'];

            $goodsOrderRefundModel->error_msg = $return_info['msg'];
            $goodsOrderRefundModel->save();

            //退款失败
            throw new Exception($return_info['msg']);
            // return $this->returnApi(202 , $return_info['msg']);
        }
    }
}
